<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\Request;
use think\facade\Cache;
use think\facade\Db;
use think\captcha\facade\Captcha;

use think\facade\Session;
use think\facade\Cookie;

class User extends Base
{

    public function register()  //用户注册方法
    {
        if($this->request->isPost()){   //表单提交
            $data = $this->request->post();

            $checked = Cache::get($data['user_email'].'code');
            if(!$checked){
                return $this->returnJson(400,'请获取验证码再提交！');
            }


            if($checked != strtolower($data['emailCheck'])){
                return $this->returnJson(400,'验证码错误，请重试！');
            }

            Cache::delete($data['user_email'].'code');  //验证通过后消除验证码
            unset($data['emailCheck']);


            $data = $this->insertTime($data);
            $data['user_pwd'] = md5($data['user_pwd']);
            $data['status'] = 0;

            Db::startTrans();
            try {
            $user_id = Db::table('user')->insertGetId($data);

            if($user_id){
                $admin_data = [
                    'admin_name'=>$data['user_account'],
                    'admin_pwd'=>$data['user_pwd'],
                    'status'=>$data['status']
                ];

                $admin_data = $this->insertTime($admin_data);

                $admin_id = Db::table('admin')->insertGetId($admin_data);

                if($admin_id){
                    $user_admin = [
                        'admin_id'=>$admin_id,
                        'user_id'=>$user_id
                    ];

                    $user_admin = $this->insertTime($user_admin);
                    $res = Db::table('user_admin')->save($user_admin);

                    if($res){
                        $admin_role = [
                            'admin_id'=>$admin_id,
                            'role_id'=>43
                        ];
                        $admin_role = $this->insertTime($admin_role);
                        $res2 = Db::table('admin_role')->save($admin_role);

                    }
                }

            }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->returnJson(400,'注册失败，请重试');
            }

            return $this->returnJson(200,'注册成功',['id'=>$user_id]);

        }

        return view();
    }

    public function haveEmail($email)   //验证邮箱是否存在
    {
        $ema = Db::table('user')->where('user_email',$email)->field('user_email')->find();

        if($ema){
            return $this->returnJson(400,'该邮箱已被注册');
        }
    }

    public function haveAccount($account)   //验证是否有账号
    {
        $acc = Db::table('user')->where('user_account',$account)->field('user_account')->find();
        if($acc){
           return $this->returnJson(400,'已有相同账号');
        }

        $admin = Db::table('admin')->where('admin_name',$account)->field('admin_name')->find();

        if($admin){
            return $this->returnJson(400,'已有相同账号');
        }
    }

    public function haveNickname($nickname)  //昵称是否存在
    {
        $nick = Db::table('user')->where('user_nickname',$nickname)->field('user_nickname')->find();

        if($nick){
            return $this->returnJson(400,'该昵称已被注册');
        }
    }

    private function returnJson($code,$msg,$data=[])
    {
        return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
    }



    public function login() //用户登录
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            if($data['type'] == 1){     //判断是什么类型的登录 如果为1 是邮箱登录
                $type = 'user_email';
                unset($data['type']);
            }else{
                $type = 'user_account';
                unset($data['type']);
            }

            if(!captcha_check($data['ccap'])){
                return $this->returnJson(400,'验证码填写错误');
            };

            unset($data['ccap']);


            $user = Db::table('user')->where([[$type,'=',$data['user_name']],['status','=',0]])->field('id,user_account,user_nickname,user_pwd,user_email,user_img')->find();

            if(!$user){
                return $this->returnJson(400,'账户错误或不存在');
            }

            if($user['user_pwd'] != md5($data['user_pwd'])){
                return $this->returnJson(400,'密码错误,请重试');
            }
            unset($user['user_pwd']);


            $code = $this->makeUserCookie($data['user_name'],$data['user_pwd']);
            Cookie::set('index_user',$code,60*60*10); //用户数据存入cookie
            Cache::set('index_'.$code,$user);  //用户数据存入缓存

            return $this->returnJson(200,'登录成功');

        };
        return view();
    }

    private function makeUserCookie($user_name,$user_pwd)  //私有的创建cookie方法 入参为用户数据
    {
        $rand = (string)rand(100000,999999);  //两边的随机数
        $str = base64_encode(md5($rand));
        $user_code = sha1(md5(base64_encode(md5($user_name.$user_pwd))));
        $code = md5($str.$user_code.$str);


        return $code;
    }


    public function sendEmailCode()     //发送邮箱验证码
    {
        $e = $this->request->get('email');
        $str = [
            1,2,3,4,5,6,7,8,9,0,
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n'
        ];
        $code = $str[rand(0,count($str)-1)].$str[rand(0,count($str)-1)].$str[rand(0,count($str)-1)].$str[rand(0,count($str)-1)].$str[rand(0,count($str)-1)];

        Cache::set($e.'code',strtolower($code),60*10);

       $email = \Email::EmailObj();


       $res = $email->sendEmail($e,$code);  //发送邮箱
       return json($res);

    }


}
